package com.situ.mall.controller.front;

import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.apache.poi.ss.usermodel.PrintCellComments;
import org.aspectj.internal.lang.annotation.ajcDeclareAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.situ.mall.entity.Cart;
import com.situ.mall.entity.Order;
import com.situ.mall.entity.OrderItem;
import com.situ.mall.entity.Product;
import com.situ.mall.entity.Shipping;
import com.situ.mall.entity.User;
import com.situ.mall.mapper.ProductMapper;
import com.situ.mall.service.ICartService;
import com.situ.mall.service.IOrderItemService;
import com.situ.mall.service.IOrderService;
import com.situ.mall.service.IProductService;
import com.situ.mall.service.IShippingService;

@Controller
@RequestMapping("/order")
public class FrontOrderItemController {

	@Autowired
	private IOrderItemService OrderItemService;
	@Autowired
	private IShippingService ShippingService;
	@Autowired
	private IOrderService OrderService;
	@Autowired
	private ICartService CartService;
	@Autowired
	private IProductService ProductService;

	// 跳转到用户订单 展示界面,还应该把值插入到order_item表
	@RequestMapping("/getorder.shtml")
	public String getorder(HttpSession session, Model model) {
		User user = (User) session.getAttribute("USER");
		// 获取userID
		Integer userId = user.getId();
		// 要根据 userID 查询 order 表 再插入到order_item表
		List<Order> cartList = OrderService.selectByUserId(userId);
		// select * from orderItem where user_id = userId;
		List<OrderItem> orderItemList = OrderItemService.selectByUserId(userId);
		model.addAttribute("orderItemList", orderItemList);
		// 在 shipping 表中查询用户联系方式和收货地址
		Shipping shippingList = ShippingService.selectByUserId(userId);
		model.addAttribute("shippingList", shippingList);
		// userID,productId,productName,productImage,价格，数量，总价。
		// 用userID查询cart表
		List<Cart> carts = CartService.select(userId);
		for (Cart cart : carts) {
			if (cart.getChecked() == 1) {
				Integer productId = cart.getProductId();
				Integer quantity = cart.getQuantity();
				Product product = ProductService.selectByPrimaryKey(productId);
				OrderItem orderItem = new OrderItem();
				// userid
				orderItem.setUserId(userId);
				// 商品ID
				orderItem.setProductId(productId);
				// 商品数量
				orderItem.setQuantity(quantity);
				// 商品图片
				orderItem.setProductImage(product.getMainImage());
				// 价格
				orderItem.setCurrentUnitPrice(product.getPrice());
				// 商品名字
				orderItem.setProductName(product.getName());
				System.out.println(orderItem);
				OrderItemService.insertSelective(orderItem);
				// OrderItemService.updateByProductId(productId);
				// 插入完成后，删除cart表中信息
				CartService.deleteByIsChecked(userId);
			}

		}

		return "/order/order_detail";
	}
}
